// 狗狗管理API服务
// 这里模拟后端API调用，实际项目中应该连接真实的后端服务
import axios from 'axios'
import ImageUrlManager from '@/utils/imageUtils' // eslint-disable-line

// 模拟数据
const mockDogs = [
  {
    id: 1,
    breed: '金毛寻回犬',
    breed_en: 'Golden Retriever',
    image1: 'https://images.unsplash.com/photo-1552053831-71594a27632d?w=300',
    image2: 'https://images.unsplash.com/photo-1583337130417-3346a1be7dee?w=300',
    image3: 'https://images.unsplash.com/photo-1605568427561-40dd23c2acea?w=300',
    image4: 'https://images.unsplash.com/photo-1543466835-00a7907e9de1?w=300',
    distribution_area: '全球广泛分布',
    weight_min: 25.0,
    weight_max: 34.0,
    height_min: 51.0,
    height_max: 61.0,
    habits: '温顺友好，喜欢游泳和捡拾游戏，需要大量运动和社交',
    care_difficulty: 5,
    characteristics: '智商高，易训练，对家庭忠诚，毛发需要定期梳理',
    temperament: '友善、可靠、值得信赖',
    life_span: '10-12年',
    origin_country: '苏格兰',
    group_type: '运动犬组',
    coat_type: '双层毛，中长毛',
    coat_color: '金色、奶油色',
    exercise_needs: 4,
    grooming_needs: 3,
    training_difficulty: 2,
    good_with_children: 1,
    good_with_pets: 1,
    apartment_friendly: 0,
    barking_level: 2,
    health_issues: '髋关节发育不良、眼部疾病、心脏病',
    special_notes: '需要大量运动空间，不适合长时间独处',
    popularity_rank: 3,
    price_range: '3000-8000元',
    status: 1,
    created_at: '2024-01-01 00:00:00',
    updated_at: '2024-01-01 00:00:00'
  },
  {
    id: 2,
    breed: '拉布拉多犬',
    breed_en: 'Labrador Retriever',
    image1: 'https://images.unsplash.com/photo-1518717758536-85ae29035b6d?w=300',
    image2: 'https://images.unsplash.com/photo-1587300003388-59208cc962cb?w=300',
    image3: 'https://images.unsplash.com/photo-1551717743-49959800b1f6?w=300',
    image4: 'https://images.unsplash.com/photo-1544568100-847a948585b9?w=300',
    distribution_area: '全球广泛分布',
    weight_min: 25.0,
    weight_max: 36.0,
    height_min: 54.0,
    height_max: 62.0,
    habits: '活泼好动，喜欢水，食欲旺盛，需要控制体重',
    care_difficulty: 5,
    characteristics: '智商极高，性格温和，是优秀的家庭伴侣和工作犬',
    temperament: '外向、活跃、友好',
    life_span: '10-14年',
    origin_country: '加拿大纽芬兰',
    group_type: '运动犬组',
    coat_type: '短毛，双层毛',
    coat_color: '黄色、黑色、巧克力色',
    exercise_needs: 5,
    grooming_needs: 2,
    training_difficulty: 1,
    good_with_children: 1,
    good_with_pets: 1,
    apartment_friendly: 0,
    barking_level: 2,
    health_issues: '髋关节和肘关节发育不良、眼部疾病、肥胖',
    special_notes: '容易发胖，需要控制饮食和充足运动',
    popularity_rank: 1,
    price_range: '2000-6000元',
    status: 1,
    created_at: '2024-01-01 00:00:00',
    updated_at: '2024-01-01 00:00:00'
  },
  // 更多数据...
]

// 模拟API延迟
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

// API服务类
class DogService {
  // 1. 品种列表查询（简化版）- GET /api/breeds/list
  static async getBreedsList() {
    try {
      const response = await axios.get('/api/breeds/list')

      if (response.data && response.data.code === 200) {
        // 转换字段名以适配前端
        // 注意：data直接是数组，不是data.list
        const convertedData = this.convertBreedFields(response.data.data || [])
        return {
          success: true,
          data: convertedData,
          message: response.data.message || '获取成功'
        }
      } else {
        return {
          success: false,
          message: response.data?.message || '获取失败'
        }
      }
    } catch (error) {
      console.error('获取品种列表失败:', error)
      return this.handleApiError(error, '获取品种列表失败')
    }
  }

  // 2. 分页获取品种列表 - GET /api/breeds/list/page
  static async getBreedsListPage(page = 1, size = 20) {
    try {
      const response = await axios.get('/api/breeds/list/page', {
        params: { page, size }
      })

      if (response.data && response.data.code === 200) {
        // 转换字段名以适配前端
        const convertedData = this.convertBreedFields(response.data.data.list || [])
        return {
          success: true,
          data: convertedData,
          total: response.data.data.total || 0,
          page: response.data.data.page || page,
          size: response.data.data.size || size,
          pages: response.data.data.pages || 1,
          message: response.data.message || '获取成功'
        }
      } else {
        return {
          success: false,
          message: response.data?.message || '获取失败'
        }
      }
    } catch (error) {
      console.error('分页获取品种列表失败:', error)
      return this.handleApiError(error, '分页获取品种列表失败')
    }
  }

  // 3. 品种详情查询（完整版）- GET /api/breeds/{id}
  static async getBreedDetail(id) {
    try {
      const response = await axios.get(`/api/breeds/${id}`)

      if (response.data && response.data.code === 200) {
        // 转换字段名以适配前端
        const convertedData = this.convertBreedFields([response.data.data])[0] || {}
        return {
          success: true,
          data: convertedData,
          message: response.data.message || '获取成功'
        }
      } else {
        return {
          success: false,
          message: response.data?.message || '获取失败'
        }
      }
    } catch (error) {
      console.error('获取品种详情失败:', error)
      return this.handleApiError(error, '获取品种详情失败')
    }
  }

  // 4. 品种编辑接口 - PUT /api/breeds/{id}
  static async updateBreed(id, breedData) {
    try {
      // 数据验证
      const validationResult = this.validateBreedData(breedData, false) // false表示部分更新
      if (!validationResult.valid) {
        return {
          success: false,
          message: validationResult.message
        }
      }

      // 转换字段名以适配后端
      const backendData = this.convertToBackendFields(breedData)

      const response = await axios.put(`/api/breeds/${id}`, backendData, {
        headers: {
          'Content-Type': 'application/json'
        }
      })

      if (response.data && response.data.code === 200) {
        // 转换返回的字段名以适配前端
        const convertedData = this.convertBreedFields([response.data.data])[0] || {}
        return {
          success: true,
          data: convertedData,
          message: response.data.message || '更新成功'
        }
      } else {
        return {
          success: false,
          message: response.data?.message || '更新失败'
        }
      }
    } catch (error) {
      console.error('更新品种失败:', error)
      return this.handleApiError(error, '更新品种失败')
    }
  }

  // 获取所有狗狗列表（保留原有方法，用于兼容）
  static async getAllDogs(params = {}) {
    await delay(500) // 模拟网络延迟

    let result = [...mockDogs]

    // 搜索过滤
    if (params.keyword) {
      result = result.filter(dog =>
        dog.breed.includes(params.keyword) ||
        dog.breed_en.toLowerCase().includes(params.keyword.toLowerCase())
      )
    }

    // 分组过滤
    if (params.group_type) {
      result = result.filter(dog => dog.group_type === params.group_type)
    }

    // 好养度过滤
    if (params.care_difficulty) {
      result = result.filter(dog => dog.care_difficulty == params.care_difficulty)
    }

    // 公寓适应性过滤
    if (params.apartment_friendly !== undefined) {
      result = result.filter(dog => dog.apartment_friendly == params.apartment_friendly)
    }

    // 分页
    const page = params.page || 1
    const pageSize = params.pageSize || 10
    const start = (page - 1) * pageSize
    const end = start + pageSize

    return {
      success: true,
      data: result.slice(start, end),
      total: result.length,
      page,
      pageSize
    }
  }
  
  // 根据ID获取狗狗详情
  static async getDogById(id) {
    await delay(300)
    
    const dog = mockDogs.find(d => d.id == id)
    if (dog) {
      return {
        success: true,
        data: dog
      }
    } else {
      return {
        success: false,
        message: '未找到该狗狗品种'
      }
    }
  }
  
  // 创建新狗狗
  static async createDog(dogData) {
    await delay(800)
    
    const newDog = {
      ...dogData,
      id: Math.max(...mockDogs.map(d => d.id)) + 1,
      status: 1,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    }
    
    mockDogs.push(newDog)
    
    return {
      success: true,
      data: newDog,
      message: '添加成功'
    }
  }
  
  // 更新狗狗信息
  static async updateDog(id, dogData) {
    await delay(800)
    
    const index = mockDogs.findIndex(d => d.id == id)
    if (index !== -1) {
      mockDogs[index] = {
        ...mockDogs[index],
        ...dogData,
        updated_at: new Date().toISOString()
      }
      
      return {
        success: true,
        data: mockDogs[index],
        message: '更新成功'
      }
    } else {
      return {
        success: false,
        message: '未找到该狗狗品种'
      }
    }
  }
  
  // 删除狗狗
  static async deleteDog(id) {
    await delay(500)
    
    const index = mockDogs.findIndex(d => d.id == id)
    if (index !== -1) {
      mockDogs.splice(index, 1)
      return {
        success: true,
        message: '删除成功'
      }
    } else {
      return {
        success: false,
        message: '未找到该狗狗品种'
      }
    }
  }
  


  // 导入狗狗品种数据
  static async importBreeds(file) {
    try {
      // 创建FormData对象
      const formData = new FormData()
      formData.append('file', file)

      // 调用真实的API (通过代理)
      const response = await axios.post('/api/breeds/import', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        timeout: 30000 // 30秒超时
      })

      // 处理API响应
      if (response.data && response.data.code === 200) {
        return {
          success: true,
          message: response.data.message || '导入成功',
          data: response.data.data || {}
        }
      } else {
        return {
          success: false,
          message: response.data?.message || '导入失败'
        }
      }
    } catch (error) {
      console.error('导入失败:', error)

      // 处理不同类型的错误
      if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error')) {
        return {
          success: false,
          message: '无法连接到服务器，请检查服务器是否正常运行'
        }
      } else if (error.response) {
        // 服务器返回了错误响应
        const errorMessage = error.response.data?.message || error.response.statusText || '服务器错误'
        return {
          success: false,
          message: `导入失败：${errorMessage} (状态码: ${error.response.status})`
        }
      } else if (error.request) {
        // 请求已发出但没有收到响应
        return {
          success: false,
          message: '请求超时，请检查网络连接'
        }
      } else {
        // 其他错误
        return {
          success: false,
          message: '导入失败：' + (error.message || '未知错误')
        }
      }
    }
  }

  // 5. 图片上传接口 - POST /api/files/upload/image
  static async uploadImage(file) {
    try {
      // 图片格式和大小验证
      const validationResult = this.validateImageFile(file)
      if (!validationResult.valid) {
        return {
          success: false,
          message: validationResult.message
        }
      }

      // 使用FormData上传文件
      const formData = new FormData()
      formData.append('file', file)

      console.log('上传文件信息:', {
        name: file.name,
        size: file.size,
        type: file.type
      })

      const response = await axios.post('/api/files/upload/image', formData, {
        // 不设置Content-Type，让浏览器自动设置包含boundary的multipart/form-data
        timeout: 30000 // 30秒超时
      })

      console.log('上传响应:', response.data)

      if (response.data && response.data.code === 200) {
        const responseData = response.data.data
        return {
          success: true,
          data: {
            url: responseData.fileUrl || responseData.url,
            filename: responseData.fileName || file.name,
            size: responseData.fileSize || file.size,
            type: responseData.contentType || file.type
          },
          message: response.data.message || '上传成功'
        }
      } else {
        return {
          success: false,
          message: response.data?.message || '上传失败'
        }
      }
    } catch (error) {
      console.error('图片上传失败:', error)

      // 详细的错误信息
      if (error.response) {
        console.error('响应状态:', error.response.status)
        console.error('响应数据:', error.response.data)
        console.error('响应头:', error.response.headers)
      }

      return this.handleApiError(error, '图片上传失败')
    }
  }



  // 图片文件验证方法
  static validateImageFile(file) {
    // 支持的图片格式
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
    const maxSize = 5 * 1024 * 1024 // 5MB

    if (!file) {
      return { valid: false, message: '请选择要上传的图片文件' }
    }

    if (!allowedTypes.includes(file.type)) {
      return {
        valid: false,
        message: '不支持的图片格式，请上传 JPEG、PNG、GIF 或 WebP 格式的图片'
      }
    }

    if (file.size > maxSize) {
      return {
        valid: false,
        message: '图片文件大小不能超过 5MB'
      }
    }

    return { valid: true }
  }

  // 品种数据验证方法
  static validateBreedData(data, isFullValidation = true) {
    const errors = []

    // 必填字段验证（仅在完整验证时检查）
    if (isFullValidation) {
      if (!data.breed || !data.breed.trim()) {
        errors.push('品种名称不能为空')
      }
      if (!data.breed_en || !data.breed_en.trim()) {
        errors.push('英文名称不能为空')
      }
    }

    // 数值范围验证
    if (data.weight_min !== undefined && data.weight_min !== null) {
      if (isNaN(data.weight_min) || data.weight_min < 0 || data.weight_min > 200) {
        errors.push('最小体重必须是0-200之间的数字')
      }
    }

    if (data.weight_max !== undefined && data.weight_max !== null) {
      if (isNaN(data.weight_max) || data.weight_max < 0 || data.weight_max > 200) {
        errors.push('最大体重必须是0-200之间的数字')
      }
    }

    if (data.weight_min && data.weight_max && data.weight_min > data.weight_max) {
      errors.push('最小体重不能大于最大体重')
    }

    if (data.height_min !== undefined && data.height_min !== null) {
      if (isNaN(data.height_min) || data.height_min < 0 || data.height_min > 150) {
        errors.push('最小身高必须是0-150之间的数字')
      }
    }

    if (data.height_max !== undefined && data.height_max !== null) {
      if (isNaN(data.height_max) || data.height_max < 0 || data.height_max > 150) {
        errors.push('最大身高必须是0-150之间的数字')
      }
    }

    if (data.height_min && data.height_max && data.height_min > data.height_max) {
      errors.push('最小身高不能大于最大身高')
    }

    // 评分字段验证（1-5分）
    const ratingFields = ['care_difficulty', 'exercise_needs', 'grooming_needs', 'training_difficulty', 'barking_level']
    ratingFields.forEach(field => {
      if (data[field] !== undefined && data[field] !== null) {
        if (isNaN(data[field]) || data[field] < 1 || data[field] > 5) {
          errors.push(`${field}必须是1-5之间的数字`)
        }
      }
    })

    // 布尔字段验证
    const booleanFields = ['good_with_children', 'good_with_pets', 'apartment_friendly']
    booleanFields.forEach(field => {
      if (data[field] !== undefined && data[field] !== null) {
        if (![0, 1, true, false].includes(data[field])) {
          errors.push(`${field}必须是布尔值`)
        }
      }
    })

    return {
      valid: errors.length === 0,
      message: errors.length > 0 ? errors.join('; ') : '验证通过'
    }
  }

  // 统一错误处理方法
  static handleApiError(error, defaultMessage) {
    if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error')) {
      return {
        success: false,
        message: '无法连接到服务器，请检查服务器是否正常运行'
      }
    } else if (error.response) {
      // 服务器返回了错误响应
      const errorMessage = error.response.data?.message || error.response.statusText || '服务器错误'
      return {
        success: false,
        message: `${defaultMessage}：${errorMessage} (状态码: ${error.response.status})`
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      return {
        success: false,
        message: '请求超时，请检查网络连接'
      }
    } else {
      // 其他错误
      return {
        success: false,
        message: defaultMessage + '：' + (error.message || '未知错误')
      }
    }
  }

  // 字段转换方法：处理后端返回数据
  static convertBreedFields(breeds) {
    if (!Array.isArray(breeds)) return []

    return breeds.map(breed => {
      // 直接使用原始数据，不进行字段名转换
      // 因为后端返回的字段名已经是前端需要的格式
      const converted = { ...breed }

      // 只进行图片URL转换
      const imageFields = [
        'standingImage', 'sittingImage', 'playingImage', 'eatingImage',
        'breed_avatar', 'standing_image', 'playing_image', 'eating_image', 'sleeping_image',
        'image1', 'image2', 'image3', 'image4', 'avatar', 'thumbnail'
      ]

      const transformedData = ImageUrlManager.transformObjectImageUrls(converted, imageFields)

      return transformedData
    })
  }

  // 字段转换方法：前端字段名 -> 后端字段名
  static convertToBackendFields(data) {
    const backendData = { ...data }

    // 将前端的下划线命名转换为后端的驼峰命名
    const fieldMapping = {
      care_difficulty: 'careDifficulty',
      breed_en: 'breedEn',
      distribution_area: 'distributionArea',
      weight_min: 'weightMin',
      weight_max: 'weightMax',
      height_min: 'heightMin',
      height_max: 'heightMax',
      life_span: 'lifeSpan',
      origin_country: 'originCountry',
      group_type: 'groupType',
      coat_type: 'coatType',
      coat_color: 'coatColor',
      exercise_needs: 'exerciseNeeds',
      grooming_needs: 'groomingNeeds',
      training_difficulty: 'trainingDifficulty',
      good_with_children: 'goodWithChildren',
      good_with_pets: 'goodWithPets',
      apartment_friendly: 'apartmentFriendly',
      barking_level: 'barkingLevel',
      health_issues: 'healthIssues',
      special_notes: 'specialNotes',
      popularity_rank: 'popularityRank',
      price_range: 'priceRange',
      // 新的图片字段映射
      breed_avatar: 'breedAvatar',
      standing_image: 'standingImage',
      playing_image: 'playingImage',
      eating_image: 'eatingImage',
      sleeping_image: 'sleepingImage'
    }

    Object.keys(fieldMapping).forEach(frontendKey => {
      if (backendData[frontendKey] !== undefined) {
        backendData[fieldMapping[frontendKey]] = backendData[frontendKey]
        delete backendData[frontendKey]
      }
    })

    return backendData
  }
}

export default DogService
